package org.xxpay.mch.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.xxpay.core.common.annotation.MethodLog;
import org.xxpay.core.common.constant.Constant;
import org.xxpay.core.common.constant.MchConstant;
import org.xxpay.core.common.constant.RetEnum;
import org.xxpay.core.common.domain.BizResponse;
import org.xxpay.core.common.domain.XxPayResponse;
import org.xxpay.core.common.exception.ServiceException;
import org.xxpay.core.entity.AgentpayPassage;
import org.xxpay.core.entity.MchAgentpayPassage;
import org.xxpay.core.entity.MchInfo;
import org.xxpay.mch.common.ctrl.BaseController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping(Constant.MCH_CONTROLLER_ROOT_PATH + "/mch_agentpay_passage_set")
public class MchAgentpayPassageSetController extends BaseController {

    @RequestMapping("/list")
    @ResponseBody
    public ResponseEntity<?> list(HttpServletRequest request) {

        judgeRecord(); //校验越权操作
        Long mchId = getUser().getId();
        MchInfo mchInfo = commonService.mchInfoService.findByMchId(mchId);
        if(mchInfo == null) {
            return ResponseEntity.ok(XxPayResponse.build(RetEnum.RET_SERVICE_MCH_NOT_EXIST));
        }


        // 得到商户已经配置的代付通道
        List<MchAgentpayPassage> mchAgentpayPassageList = commonService.mchAgentpayPassageService.selectAllByMchId(mchId);
        Map<String, MchAgentpayPassage> mchAgentpayPassageMap = new HashMap<>();
        for(MchAgentpayPassage mchAgentpayPassage : mchAgentpayPassageList) {
            mchAgentpayPassageMap.put(String.valueOf(mchAgentpayPassage.getAgentpayPassageId()), mchAgentpayPassage);
        }
        // 得到所有代付通道
        AgentpayPassage queryAgentpayPassage = new AgentpayPassage();
        queryAgentpayPassage.setStatus(MchConstant.PUB_YES);
        queryAgentpayPassage.setBelongInfoType(MchConstant.SYSTYPE_MCH);
        queryAgentpayPassage.setBelongInfoId(getUser().getId());
        List<AgentpayPassage> agentpayPassageList = commonService.agentpayPassageService.selectAll(queryAgentpayPassage);
        Map<String, AgentpayPassage> agentpayPassageMap = new HashMap<>();
        for(AgentpayPassage agentpayPassage : agentpayPassageList) {
            agentpayPassageMap.put(String.valueOf(agentpayPassage.getId()), agentpayPassage);
        }
        // 合并后返回的商户代付通道
        List<JSONObject> objects = new LinkedList<>();
        for(AgentpayPassage agentpayPassage : agentpayPassageList) {
            MchAgentpayPassage mchAgentpayPassage = mchAgentpayPassageMap.get(String.valueOf(agentpayPassage.getId()));
            if(mchAgentpayPassage == null) {
                mchAgentpayPassage = new MchAgentpayPassage();
                mchAgentpayPassage.setMchId(mchId);
                mchAgentpayPassage.setAgentpayPassageId(agentpayPassage.getId());
                mchAgentpayPassage.setStatus(MchConstant.PUB_NO);
                mchAgentpayPassage.setIsDefault(MchConstant.PUB_NO);
            }
            JSONObject object = (JSONObject) JSON.toJSON(mchAgentpayPassage);
            object.put("passageName", agentpayPassage.getPassageName());
            objects.add(object);
        }
        return ResponseEntity.ok(XxPayResponse.buildSuccess(objects));
    }

    /**
     * 查询
     * @return
     */
    @RequestMapping("/get")
    @ResponseBody
    public ResponseEntity<?> get(HttpServletRequest request) {

        judgeRecord(); //校验越权操作
        JSONObject param = getJsonParam(request);
        Long mchId = getUser().getId();
        MchInfo mchInfo = commonService.mchInfoService.findByMchId(mchId);
        if(mchInfo == null) {
            return ResponseEntity.ok(XxPayResponse.build(RetEnum.RET_SERVICE_MCH_NOT_EXIST));
        }
        Integer agentpayPassageId = getIntegerRequired(param, "agentpayPassageId");
        AgentpayPassage agentpayPassage = commonService.agentpayPassageService.findById(agentpayPassageId);
        if(agentpayPassage == null) return ResponseEntity.ok(XxPayResponse.buildSuccess(null));

        MchAgentpayPassage mchAgentpayPassage = commonService.mchAgentpayPassageService.findByMchIdAndAgentpayPassageId(mchId, agentpayPassageId);
        if(mchAgentpayPassage == null) {
            mchAgentpayPassage = new MchAgentpayPassage();
            mchAgentpayPassage.setMchId(mchId);
            mchAgentpayPassage.setAgentpayPassageId(agentpayPassageId);
            mchAgentpayPassage.setIsDefault(MchConstant.PUB_NO);
            mchAgentpayPassage.setStatus(MchConstant.PUB_NO);
            mchAgentpayPassage.setMchFeeType(MchConstant.FEE_TYPE_FIX); //默认固定收费
        }
        JSONObject object = (JSONObject) JSON.toJSON(mchAgentpayPassage);
        object.put("passageName", agentpayPassage.getPassageName());
        object.put("agentId", mchInfo.getAgentId() == null ? "" : mchInfo.getAgentId());
        return ResponseEntity.ok(XxPayResponse.buildSuccess(object));
    }

    @RequestMapping("/update")
    @ResponseBody
    @MethodLog( remark = "配置商户代付通道" )
    public ResponseEntity<?> update(HttpServletRequest request) {

        judgeRecord(); //校验越权操作

        JSONObject param = getJsonParam(request);
        // 将参数有字符元转为长整型分
        handleParamAmount(param, "maxEveryAmount", "mchFeeEvery", "inFeeEvery", "onBtbInMaxEveryAmount", "onBtbInMinEveryAmount", "onBtcInMaxEveryAmount", "onBtcInMinEveryAmount");
        MchAgentpayPassage mchAgentpayPassage = getObject(param, MchAgentpayPassage.class);
        // 修改
        int count;
        if(mchAgentpayPassage.getId() != null) {
            // 修改

            judgeRecord(mchAgentpayPassage.getId()); //校验越权操作

            if(mchAgentpayPassage.getMchFeeType() == MchConstant.FEE_TYPE_RATE){ //费率

                if(mchAgentpayPassage.getMchFeeRate() == null || mchAgentpayPassage.getMchFeeRate().compareTo(BigDecimal.ZERO) <= 0){
                    throw ServiceException.build(RetEnum.RET_COMM_PARAM_ERROR);
                }

            }else if(mchAgentpayPassage.getMchFeeType() == MchConstant.FEE_TYPE_FIX){ //固定费用

                if(mchAgentpayPassage.getMchFeeEvery() == null || mchAgentpayPassage.getMchFeeEvery() <= 0){
                    throw ServiceException.build(RetEnum.RET_COMM_PARAM_ERROR);
                }
            }else if(mchAgentpayPassage.getMchFeeType() == MchConstant.FEE_TYPE_RATE_AND_FIX){ //费率 + 费用
                if(mchAgentpayPassage.getMchFeeRate() == null || mchAgentpayPassage.getMchFeeRate().compareTo(BigDecimal.ZERO) <= 0){
                    throw ServiceException.build(RetEnum.RET_COMM_PARAM_ERROR);
                }
                if(mchAgentpayPassage.getMchFeeEvery() == null || mchAgentpayPassage.getMchFeeEvery() <= 0){
                    throw ServiceException.build(RetEnum.RET_COMM_PARAM_ERROR);
                }
            }

            if(mchAgentpayPassage.getAgentpayPassageAccountId() == null) mchAgentpayPassage.setAgentpayPassageAccountId(0);
            if(mchAgentpayPassage.getIsDefault() == 1) {
                // 修改该商户其他代付通道为非默认
                MchAgentpayPassage updateMchAgentpayPassage1 = new MchAgentpayPassage();
                updateMchAgentpayPassage1.setIsDefault(MchConstant.PUB_NO);
                commonService.mchAgentpayPassageService.updateByMchId(updateMchAgentpayPassage1, getUser().getId());
            }
            count = commonService.mchAgentpayPassageService.update(mchAgentpayPassage);
        }else {
            // 新增

            mchAgentpayPassage.setMchId(getUser().getId());

            if(mchAgentpayPassage.getMchFeeType() == MchConstant.FEE_TYPE_RATE){ //费率

                if(mchAgentpayPassage.getMchFeeRate() == null || mchAgentpayPassage.getMchFeeRate().compareTo(BigDecimal.ZERO) <= 0){
                    throw ServiceException.build(RetEnum.RET_COMM_PARAM_ERROR);
                }

            }else if(mchAgentpayPassage.getMchFeeType() == MchConstant.FEE_TYPE_FIX){ //固定费用

                if(mchAgentpayPassage.getMchFeeEvery() == null || mchAgentpayPassage.getMchFeeEvery() <= 0){
                    throw ServiceException.build(RetEnum.RET_COMM_PARAM_ERROR);
                }
            }else if(mchAgentpayPassage.getMchFeeType() == MchConstant.FEE_TYPE_RATE_AND_FIX){ //费率 + 费用
                if(mchAgentpayPassage.getMchFeeRate() == null || mchAgentpayPassage.getMchFeeRate().compareTo(BigDecimal.ZERO) <= 0){
                    throw ServiceException.build(RetEnum.RET_COMM_PARAM_ERROR);
                }
                if(mchAgentpayPassage.getMchFeeEvery() == null || mchAgentpayPassage.getMchFeeEvery() <= 0){
                    throw ServiceException.build(RetEnum.RET_COMM_PARAM_ERROR);
                }
            }

            if(mchAgentpayPassage.getIsDefault() == 1) {
                // 修改该商户其他代付通道为非默认
                MchAgentpayPassage updateMchAgentpayPassage1 = new MchAgentpayPassage();
                updateMchAgentpayPassage1.setIsDefault(MchConstant.PUB_NO);
                commonService.mchAgentpayPassageService.updateByMchId(updateMchAgentpayPassage1, mchAgentpayPassage.getMchId());
            }
            count = commonService.mchAgentpayPassageService.add(mchAgentpayPassage);
        }
        if(count == 1) return ResponseEntity.ok(BizResponse.buildSuccess());
        return ResponseEntity.ok(BizResponse.build(RetEnum.RET_COMM_OPERATION_FAIL));
    }

    /** 校验账号类型和获取的数据是否合法 **/
    private void judgeRecord(){

        //当前登录用户不属于私有商户
        if(this.getUser().getType() != MchConstant.MCH_TYPE_PRIVATE){
            throw new ServiceException(RetEnum.RET_MCH_PERMISSION_ERROR);
        }
    }

    /** 校验账号类型和获取的数据是否合法 **/
    private MchAgentpayPassage judgeRecord(Integer recordId){

        //当前登录用户是否属于私有商户
        judgeRecord();

        //判断是否越权查看
        MchAgentpayPassage record = commonService.mchAgentpayPassageService.findById(recordId);
        if(record == null || !record.getMchId().equals(this.getUser().getId())){
            throw new ServiceException(RetEnum.RET_MCH_PERMISSION_ERROR);
        }
        return record;
    }



}
